<template>
  <dd-container>
    <dd-card class="box-card box-card2">
      <!-- 数据信息 -->
      <dd-table ref="menuTable" 
        rowKey="id" 
        :data="departmentTree" 
        :option="treeOption" 
        :screen="{ pageIndex: 1, pageSize: 10 }"
        :treeProps="{ children: 'subDepartment', hasChildren: 'hasChildren' }" 
        :routePath="$route.path"
        @rowClick="rowClick"
        @selectionDelete="selectionDelete"
        height="25vh">
        <!-- 占位用的，解决展开收起跑到左边去的问题 -->
        <template slot="condition">
          <el-form-item label="请输入部门名称">
          </el-form-item>
        </template>
        <template slot="operation">
          <el-form-item>
            <el-button type="add" size="small" @click="openDialog('add')" v-if="showButton($route.path, '新增')">新增</el-button>
          </el-form-item>
        </template>
        <el-table-column prop="name" label="部门名称" align="start" width="180">
          <template slot-scope="scope">
            {{ scope.row.name ? scope.row.name : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="shortName" label="部门简称" align="start" width="120">
          <template slot-scope="scope">
            {{ scope.row.shortName ? scope.row.shortName : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="部门描述" align="start" width="100">
          <template slot-scope="scope">
            {{ scope.row.description ? scope.row.description : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="contact" label="联系人员" align="center" width="80">
          <template slot-scope="scope">
            {{ scope.row.contact ? scope.row.contact : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="telephone" label="联系电话" align="center" width="120">
          <template slot-scope="scope">
            {{ scope.row.telephone ? scope.row.telephone : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="email" label="部门邮箱" align="center" width="120">
          <template slot-scope="scope">
            {{ scope.row.email ? scope.row.email : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="420" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="warning" :disabled="scope.row.level === 3" @click="openDialog('subAdd', { parentId: scope.row.id })" v-if="showButton($route.path, '添加子部门')">添加子部门
            </el-button>
            <el-button size="mini" type="warning" @click="addPerson(scope.row)" v-if="showButton($route.path, '添加人员')">添加人员</el-button>
            <el-button size="mini" type="info" @click="openDialog('info', scope.row)" v-if="showButton($route.path, '详情')">详情</el-button>
            <el-button size="mini" type="edit" @click="openDialog('edit', scope.row)" v-if="showButton($route.path, '编辑')">编辑</el-button>
            <el-button size="mini" type="del" @click="handleDelete(scope.row)" v-if="showButton($route.path, '删除')">删除</el-button>
          </template>
        </el-table-column>
      </dd-table>
      <handleDialog :visible.sync="dialogVisible" :modelType="modelType" :modelData="modelData" @loadList="getDepartmentGroup"></handleDialog>
      <selectUserDialog :visible.sync="userDialogVisible" @selectedItem="selectedUser"></selectUserDialog>
    </dd-card>
    <dd-card class="box-card box-card2">
      <dd-table 
        ref="dataTable"
        rowKey="id" 
        :data="tableData"
        :option="option" 
        :screen="searchForm" 
        :loadingData="loadDataList"
        height="25vh">
        <!-- 占位用的，解决展开收起跑到左边去的问题 -->
        <template slot="condition">
          <el-form-item label="请输入用户名称">
            <el-input v-model="searchForm.name" placeholder="请输入用户名称" clearable></el-input>
          </el-form-item>
        </template>
        <template slot="operation">
          <el-form-item>
            <el-button type="search" size="small" @click="onSearch" v-if="showButton($route.path, '查询')">查询</el-button>
          </el-form-item>
        </template>
        <el-table-column label="用户昵称" align="center" width="150">
          <template slot-scope="scope">
            {{ scope.row.name || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="用户账户" align="center" width="150">
          <template slot-scope="scope">
            {{ scope.row.username || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="手机号" align="center" width="150">
          <template slot-scope="scope">
            {{ scope.row.mobile || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="电子邮箱" align="center" width="200">
          <template slot-scope="scope">
            {{ scope.row.email || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="操作" align="center" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="del" @click="deletePerson(scope.row)" v-if="showButton($route.path, '删除人员')">删除人员</el-button>
          </template>
        </el-table-column>
      </dd-table>
    </dd-card>
  </dd-container>
</template>

<script>
import { mapGetters } from 'vuex';
import handleDialog from './dialog/handleDialog.vue';
import selectUserDialog from './dialog/selectUserDialog.vue';

export default {
  components: { handleDialog, selectUserDialog },
  data() {
    return {
      searchForm: {
        pageIndex: 1,
        pageSize: 10,
        name: '',
      },
      option: {
        total: 0,
        operation: true,
        loading: false,
        expandHide: true,
        dialogTable: true
      },
      treeOption: {
        total: 0,
        loading: true,
        operation: true,
        expandHide: true,
        dialogTable: true,
        selection: true
      },
      dialogVisible: false,
      userDialogVisible: false,
      modelType: '',
      modelData: {},
      departmentTree: [],
      tableData: [],
      departmentId: '',
      departmentName: '',
    };
  },
  computed: {
    ...mapGetters('ddAdmin/menu', ['showButton'])
  },
  mounted() {
    this.getDepartmentGroup();
  },
  methods: {
    // 搜索过滤
    onSearch() {
      if(!this.searchForm.departmentId) {
        return;
      }
      this.searchForm.pageIndex = this.$options.data().searchForm.pageIndex;
      this.loadDataList();
    },
    // 获取分组树形结构数据
    async getDepartmentGroup() {
      try {
        // 查询所有部门
        let result = await this.$api.department.list({ pageIndex: 1, pageSize: 9999 });
        let allData = result.value;
        // 一级分组
        let parentGroup = allData.filter(item => !item.parentId);
        // 一级分组赋层级
        parentGroup.forEach( element => {
          element['level'] = 1;
        })
        // 子分组
        let childGroup = allData.filter(item => item.parentId);
        // 生成树状数据
        function translator(parents, childrens, level) {
          parents.forEach( element => {
            childrens.forEach( (children, index) => {
              if (children.parentId == element.id) {
                // 赋予层级
                children['level'] = level;
                // 添加到父分组子列表
                element.subDepartment ? element.subDepartment.push(children) : element.subDepartment = [children];
                // 从子分组删除
                let temp = JSON.parse(JSON.stringify(childrens));
                temp.splice(index, 1);
                translator([children], temp, level + 1);
              }
            })
          })
        }
        // 生成菜单树
        translator(parentGroup, childGroup, 2);
        this.departmentTree = parentGroup;
        this.treeOption.total = this.departmentTree.length;
        this.treeOption.loading = false;
      } catch (error) {
        console.log(error);
        this.treeOption.loading = false;
      }
    },
    // 载入列表
    async loadDataList() {
      try {
        let res = await this.$api.user.findUserList(this.searchForm);
        let count = await this.$api.user.findUserListMax(this.searchForm);
        this.option.total = count.value;
        this.tableData = res.value;
        this.option.loading = false;
      } catch (error) {
        console.log(error);
        this.option.loading = false;
      }
    },
    // 搜索用户
    searchUser() {
      this.option.loading = true;
      this.searchForm.departmentId = this.departmentId;
      this.onSearch();
    },
    // 添加部门人员
    addPerson(row) {
      this.departmentId = row.id;
      this.userDialogVisible = true;
    },
    // 选择用户
    selectedUser(item) {
      this.$api.user
        .bindDepartment({ departmentId: this.departmentId, id: item.id})
        .then((res) => {
          this.$message.success('关联成功');
          this.searchUser();
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 打开弹窗
    openDialog(modelType, modelData) {
      this.modelType = modelType;
      this.modelData = modelData === undefined ? {} : JSON.parse(JSON.stringify(modelData));
      this.dialogVisible = true;
    },
    // 点击表格单行显示该部门分组关联人员
    rowClick(row, column, event) {
      this.departmentId = row.id;
      this.departmentName = row.name;
      this.searchUser();
    },
    // 删除
    handleDelete(row) {
      let _this = this;
      this.$confirm(`此操作将永久删除 "${row.name}" 部门, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose(action, instance, done) {
          if (action == 'confirm') {
            this.$api.department
              .deleteById(row.id)
              .then((res) => {
                this.$message.success('删除成功');
                done();
                _this.getDepartmentGroup();
                _this.loadDataList();
              })
              .catch((error) => {
                console.log(error);
              });
          } else {
            done();
          }
        },
      })
        .then(() => { })
        .catch((err) => {
          this.$message.info('已取消删除');
        });
    },

    /**
     * 删除表格复选项
     * @param {Object} selection 复选项
     */
    async selectionDelete(selection) {
      try {
        let ids = selection.map(item => {
          return item.id
        })
        await this.$api.department.deleteBatch(ids)
        this.getDepartmentGroup();
        this.$message.success('删除成功');
      } catch (error) {
        this.$message.error(error.description);
      }
    },

    deletePerson(row) {
      let _this = this;
      alert(_this.departmentId)
      this.$confirm(`此操作将解除用户 "${row.name}" 部门关联, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose(action, instance, done) {
          if (action == 'confirm') {
            this.$api.user
              .unBindDepartment({ departmentId: _this.departmentId, id: row.id})
              .then((res) => {
                this.$message.success('解除成功');
                done();
                _this.searchUser();
              })
              .catch((error) => {
              });
          } else {
            done();
          }
        },
      }).then(() => { })
        .catch((err) => {
          this.$message.info('已取消解除');
        });
    }
  }
};
</script>

<style lang='scss' scoped>
.el-button {
  margin-bottom: 6px;
}
.box-card {
    margin-bottom: 20px;
}
</style>